package com.macro.mall.controller;

import cn.hutool.core.util.StrUtil;
import com.macro.mall.common.api.CommonPage;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.model.UmsCommunity;
import com.macro.mall.model.UmsMember;
import com.macro.mall.model.UmsMemberAll;
import com.macro.mall.model.UmsMemberLog;
import com.macro.mall.service.UmsCommunityService;
import com.macro.mall.service.UmsMemberGroupService;
import com.macro.mall.service.UmsMemberLogService;
import com.macro.mall.service.UmsMemberService;
import com.macro.mall.utils.ProvinceUtil;
import com.macro.mall.utils.ReadExcelUtil;
import com.macro.mall.vo.UserImportVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 后台会员管理Controller
 * Created by gaodx on 2020/08/06
 */
@Controller
@Api(tags = "UmsMemberController", description = "后台会员管理")
@RequestMapping("/member")
@Slf4j
public class UmsMemberController {
    private static final String KEY = "USER_IMPORT";

    @Autowired
    private UmsMemberService memberService;
    @Autowired
    private UmsMemberLogService umsMemberLogService;
    @Autowired
    private UmsCommunityService umsCommunityService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ReadExcelUtil readExcelUtil;
    @Autowired
    private ProvinceUtil provinceUtil;
    @Autowired
    private UmsMemberGroupService umsMemberGroupService;



    @ApiOperation("查询所有会员信息")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody

    public CommonResult list(
                             @RequestParam(value = "username", required = false) String username,
                             @RequestParam(value = "name", required = false) String name,
                             @RequestParam(value = "community", required = false) String community,
                             @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                             @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        List<UmsMember> member = memberService.selectAllByUmsMember(username,name, community, pageSize, pageNum);
        return CommonResult.success(CommonPage.restPage(member));
    }

    @ApiOperation("后台更新会员信息")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult update(@ApiParam(value = "请求报文") @RequestBody UmsMember umsMember) {
        memberService.updateUmsMemberSelective(umsMember);
        return CommonResult.success(null);
    }

    @ApiOperation("后台查询会员信息")
    @RequestMapping(value = "/getMenberById", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult getMenberById(@ApiParam(value = "id") @RequestParam(value = "id", required = true) String id) {
        UmsMember umsMember = memberService.selectUmsMemberById(id);
        return CommonResult.success(umsMember);
    }

    @ApiOperation("后台删除会员信息")
    @RequestMapping(value = "/delMenberById", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult deleteMenberById(@ApiParam(value = "id") @RequestParam(value = "id", required = true) String id) {
        memberService.deleteUmsMemberById(id);
        return CommonResult.success(null);
    }


    @ApiOperation("查询会员审核列表")
    @RequestMapping(value = "/auditList", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult 查询会员审核信息信息(
            @RequestParam(value = "username", required = false) String username,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize ) {
        List<UmsMemberLog> member = umsMemberLogService.find(username, pageNum, pageSize);
        return CommonResult.success(CommonPage.restPage(member));
    }

    @ResponseBody
    @ApiOperation("查询会员审核信息")
    @RequestMapping(value = "/auditById", method = RequestMethod.GET)
    public CommonResult auditById(
            @RequestParam(value = "id", required = false) Long id,
            @RequestParam(value = "userName", required = false) String userName) {
        UmsMemberLog one = umsMemberLogService.findOne(id,userName);
        return CommonResult.success(one);
    }

    @ResponseBody
    @ApiOperation("审核修改")
    @RequestMapping(value = "/updateAudit", method = RequestMethod.POST)
    public CommonResult updateAudit(
             @RequestBody UmsMemberLog request) {
        umsMemberLogService.updateNotNullById(request);
        return CommonResult.success(null);
    }

    @ApiOperation("查询委员会入住居民列表")
    @RequestMapping(value = "/listForCheckIn", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult listForCheckIn(
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "phone", required = false) String phone,
            @RequestParam(value = "identityInfo", required = false) String identityInfo,
            @RequestParam(value = "isVolunteer", required = false) String isVolunteer,
            @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {

        UmsMemberAll queryMember = new UmsMemberAll();
        if (!StrUtil.isEmpty(name)) {
            queryMember.setName(name);
        }
        if (!StrUtil.isEmpty(phone)) {
            queryMember.setPhone(phone);
        }
        if (StrUtil.isNotEmpty(identityInfo)) {
            queryMember.setIdentityInfo(identityInfo);
        }
        if (StrUtil.isNotEmpty(isVolunteer)) {
            queryMember.setIsVolunteer(isVolunteer);
        }
        List<UmsMemberAll> member = memberService.listForCheckIn(queryMember, pageSize, pageNum);
        return CommonResult.success(CommonPage.restPage(member));
    }
    @ApiOperation(value = "获取会员信息（包含入住信息与志愿者信息）")
    @RequestMapping(value = "/getMemberAllById", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult getMemberAllById(Long memberId) {
        if(memberId==null){
            return CommonResult.unauthorized(null);
        }
        UmsMemberAll memberAll = memberService.getMemberAllById(memberId);
        return CommonResult.success(memberAll);
    }
    @ApiOperation(value = "删除入住信息")
    @RequestMapping(value = "/delCheckInByExtendId", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult delCheckInByExtendId(Long extendId) {
        memberService.delCheckInByExtendId(extendId);
        return CommonResult.success("保存成功");
    }
    @ApiOperation(value = "删除志愿者信息信息")
    @RequestMapping(value = "/delVolunteerByExtendId", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult delVolunteerByExtendId(Long extendId) {
        memberService.delVolunteerByExtendId(extendId);
        return CommonResult.success("保存成功");
    }


    @ResponseBody
    @ApiOperation(value = "导入-用户信息导入", notes = "导入-用户信息导入接口")
    @PostMapping(value = "/userImport")
    public CommonResult boothUpload(@ApiParam(value = "文件") @RequestParam("file") MultipartFile file,
                                    @RequestParam(value = "userId", required = false) String userId,
                                    @RequestParam(value = "userName", required = false) String userName) throws IOException {
        Map<String, Object> map = new HashMap<>();
        try {
//           ValueOperations objOps = redisTemplate.opsForValue();
//            boolean bSet = objOps.setIfAbsent(KEY, "processing");
//            if (!bSet) {
//                String message = "processor is running, cannot start again.";
//                log.error(message + " the key is redis is :" + KEY);
//                return CommonResult.failed("请稍后,等待上次文件处理完成后再次尝试.");
//            }
            InputStream inputStream = file.getInputStream();
            Workbook wb = ReadExcelUtil.chooseWorkbook("file.xlsx", inputStream);
            UserImportVO vo = new UserImportVO();
            Map<String, Object> stringObjectMap = readExcelUtil.readDataListT(wb, vo, 1, 2, 0, map);
            String result = (String) stringObjectMap.get("result");
            String message = (String) stringObjectMap.get("message");
            if (!result.equals("0000")) {
                return CommonResult.failed(message);
            }
            List<UserImportVO> data = (List<UserImportVO>) stringObjectMap.get("data");
            log.info("boothUploadVOS size : {}", data.size());
            for (UserImportVO one : data) {
                UmsCommunity one1 = umsCommunityService.findOne(Long.parseLong(one.getCommunityId()+""));
                UmsMember build = UmsMember.builder().build();
                BeanUtils.copyProperties(one, build);
                build.setCommunityId(one1.getId().intValue());
                build.setCommunityName(one1.getCommunityName());
                build.setUsername(one.getPhone());
                build.setGender(Integer.parseInt(one.getGender()));
                List<UmsMember> umsMembers = memberService.selectAllByUmsMember(one.getPhone(), null, null, 1, 1);
                if(umsMembers.size() == 0) {
                    build.setProvince(provinceUtil.getCodeJson(build.getProvince()));
                    build.setCity(provinceUtil.getCodeJson(build.getCity()));
                    build.setArea(provinceUtil.getCodeJson(build.getArea()));
                    memberService.saveUmsMemberSelective(build);
                    UmsMemberLog memberLog = UmsMemberLog.builder().userId(build.getId().toString()).name(build.getName()).phone(build.getUsername()).floor(build.getFloor()).
                            idCard(build.getIdCard()).province(build.getProvince()).city(build.getCityCode()).area(build.getCountyCode())
                            .status("01").communityId(StringUtils.isEmpty(build.getCommunityId())?null:build.getCommunityId().longValue())
                            .communityName(build.getCommunityName()).userIdentity(build.getUserIdentity()).operationId(userId).operationName(userName).build();
                    umsMemberLogService.saveNotNull(memberLog);
                    umsMemberGroupService.saveMemberGroups(build,one.getUserIdentity());
                }else {
                    UmsMember umsMember = umsMembers.get(0);
                    build.setId(umsMember.getId());
                    String userType = umsMember.getUserType();
                    if(!build.getUserType().equals(userType)) {
                        build.setUserType("03");
                    }
                    build.setProvince(provinceUtil.getCodeJson(build.getProvince()));
                    build.setCity(provinceUtil.getCodeJson(build.getCity()));
                    build.setArea(provinceUtil.getCodeJson(build.getArea()));
                    memberService.updateMemberSelective(build);
                    umsMemberGroupService.saveMemberGroups(build,one.getUserIdentity());
                }
            }
            if (data.size() < 1) {
                return CommonResult.failed();
            }
        } catch (Exception e) {
            log.error("上传失败", e);
            return CommonResult.failed();
        } finally {
            Boolean delete = redisTemplate.delete(KEY);
        }
        return CommonResult.success(null);
    }



}
